﻿//------------------------------------------------------------
// Author: 烟雨迷离半世殇
// Mail: 1778139321@qq.com
// Data: 2019年12月30日 21:37:30
//------------------------------------------------------------



namespace NKG_MVVM_UI
{
    public abstract class ATempView<T> : AViewLogic, IViewData<T> where T : AViewModel
    {
        private bool _hasBinded;
        protected readonly PropertyBinder<T> Binder = new PropertyBinder<T>();
        public readonly BindableProperty<T> ViewModelProperty = new BindableProperty<T>();

        public T BindingContext
        {
            get { return ViewModelProperty.Value; }
            set
            {
                if (!_hasBinded)
                {
                    //无论ViewModel的Value怎样变化，只对OnValueChanged事件监听(绑定)一次
                    ViewModelProperty.OnValueChanged += OnBindingContextChanged;
                    _hasBinded = true;
                }

                //触发OnValueChanged事件
                ViewModelProperty.Value = value;
            }
        }

        /// <summary>
        /// 绑定的上下文发生改变时的响应方法
        /// </summary>
        public virtual void OnBindingContextChanged(T oldValue, T newValue)
        {
            Binder.Unbind(oldValue);
            Binder.Bind(newValue);
        }
    }
}